<?php

namespace Models;

/**
 * Description of User
 *
 * @author Admin
 */
class Vocabulary extends \Core\Base\Table
{
	
	public function getList($limit = null)
	{
		$rowset = $this->_db->select('SELECT * FROM vocabulary ORDER BY id DESC {LIMIT ?d}', ($limit ? $limit : DBSIMPLE_SKIP));
		
		foreach($rowset as $i => $row)
		{
			$words = $this->_db->select('SELECT * FROM word WHERE vocabulary_id = ?d LIMIT 10', $row['id']);
			$rowset[$i]['words'] = $words;
		}
		
		return $rowset;
	}
	
	public function getRandomCart($limit, $userId = null)
	{
		$rowset = $this->_db->select('SELECT * FROM vocabulary {WHERE user_id = ?d} ORDER BY RAND() LIMIT ?d', ($userId ? $userId : DBSIMPLE_SKIP), $limit);
		
		foreach($rowset as $i => $row)
		{
			$words = $this->_db->select('SELECT * FROM word WHERE vocabulary_id = ?d ORDER BY RAND() LIMIT 10', $row['id']);
			$rowset[$i]['words'] = $words;
		}
		
		return $rowset;
	}
	
	public function getById($id)
	{
		if(!$id || $id < 1)
			return array();

		$row = $this->_db->selectRow('SELECT * FROM vocabulary WHERE id = ?d', $id);
		
		if($row)
		{
			$words = $this->_db->select('SELECT * FROM word WHERE vocabulary_id = ?d', $row['id']);
			$row['words'] = $words;
		}
		
		return $row;
	}
	
	public function addCart($userId, $data, $lang)
	{
		$data['vocabulary']['user_id'] = $userId;
		
		$itemId = 0;
		$words = array();
		
		if(!empty($data['id']))
		{
			$itemId = $data['id'];
			
			$this->_db->query('UPDATE vocabulary SET ?a WHERE id = ?d', $data['vocabulary'], $itemId);
			
			$row = $this->getById($itemId);
			if($row && !empty($row['words']))
			{
				foreach($row['words'] as $word)
				{
					$words[$word['id']] = $word['word'];
				}
			}
		}
		else
		{
			$itemId = $this->_db->query('INSERT INTO vocabulary (?#) VALUES (?a)', array_keys($data['vocabulary']), array_values($data['vocabulary']));
		}
		
		foreach($data['words']['word'] as $i => $row)
		{
			if(strlen($data['words']['word'][$i]) > 0 && strlen($data['words']['translate'][$i]) > 0)
			{
				$item = array();
				$item['user_id'] = $userId;
				$item['word'] = $data['words']['word'][$i];
				$item['translate'] = $data['words']['translate'][$i];
				$item['lang'] = $lang;

				if(in_array($data['words']['word'][$i], $words))
				{
					$id = array_search($data['words']['word'][$i], $words);
					$this->_db->query('UPDATE word SET ?a WHERE id = ?d', $item, $id);
					
					unset($words[$id]);
				}
				else
				{
					$item['vocabulary_id'] = $itemId;
					
					$this->_db->query('INSERT INTO word (?#) VALUES (?a)', array_keys($item), array_values($item));
				}
			}
		}
		
		if(count($words) > 0)
		{
			$this->_db->query('DELETE FROM word WHERE id IN(?a)', array_keys($words));
		}
		
		return $itemId;
	}
	
}
